<?php
#
# REQUIRE
#
require_once dirname(__FILE__).'/__c.OpenID.php';

#
# SECURITY POLICIES
#
if ($PARAMS['_action'] != 'logout') {
	$CONFIG['session.secure'] = false;
}

#
# GENERAL ACTIONS
#
function action_is_authenticated() {
	if (is_authenticated()) {
		return success();
	} else {
		return failure();
	}
}

function action_logout($p) {
	global $CONFIG;

	deauthenticate();

	if (isset($p['continue']) && is_local_url($p['continue'])) {
		redirect($p['continue']);
	} else {
		redirect($CONFIG['openid.onlogout']);
	}
}

function action_login($p) {
	return action_default($p);
}

#
# DEFAULT ACTION
#
function action_default($p) {
	global $CONFIG;

	if (is_authenticated()) {
		redirect($CONFIG['openid.onlogin']);
	}

	if (isset($p['openid_mode']) && $p['openid_mode'] == 'id_res') {
		$openid = new OpenID;
		$openid->SetIdentity($p['openid_identity']);

		if ($openid->ValidateWithServer() == true) {
			$data = array();

			foreach ($p as $key => $val) {
				if (substr($key, 0, 12) == 'openid_sreg_') {
					$data[substr($key, 12, strlen($key))] = $val;
					$data[substr($key, 24, strlen($key))] = $val;
				}
			}

			$p['openid_identity'] = $openid->OpenID_Standarize($p['openid_identity']);

			authenticate($p['openid_identity'], $data);

			if (isset($_SESSION['_openid.continue'])) {
				$url = $_SESSION['_openid.continue'];

				unset($_SESSION['_openid.continue']);

				redirect($url);
			} else {
				redirect($CONFIG['openid.onlogin']);
			}
		} else if ($openid->IsError() == true) {
			unset($_SESSION['_openid.continue']);

			redirect($CONFIG['openid.onerror']);
		} else {
			unset($_SESSION['_openid.continue']);

			redirect($CONFIG['openid.onfail']);
		}
	} else if (isset($p['openid_mode']) && $p['openid_mode'] == 'cancel') {
		unset($_SESSION['_openid.continue']);

		redirect($CONFIG['openid.oncancel']);
	} else if (isset($p['user_ID'])) {
		unset($_SESSION['_openid.continue']);

		if (strlen($p['user_ID']) == 255) {
			return error('user identity too long!');
		}

		if (isset($p['continue']) && is_local_url($p['continue'])) {
			$_SESSION['_openid.continue'] = $p['continue'];
		}

		$openid = new OpenID;
		$openid->SetIdentity($p['user_ID']);
		$openid->SetTrustRoot((isset($_SERVER['HTTPS'])?'https://':'http://').$_SERVER['HTTP_HOST']);
		$openid->SetRequiredFields($CONFIG['openid.fields.required']);
		$openid->SetOptionalFields($CONFIG['openid.fields.optional']);

		if ($openid->GetOpenIDServer()) {
			$openid->SetApprovedURL((isset($_SERVER['HTTPS'])?'https://':'http://').$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
			$openid->Redirect();
		} else {
			redirect($CONFIG['openid.onerror']);
		}
	}
}
